<?php
/**
 * Created by PhpStorm.
 * User: wangsong
 * Time: 2018/5/28 10:51
 */

namespace App\Project\Version;

class Composer implements Executable
{
    protected $command;

    protected $packages = [];

    protected $options = [];

    protected $mode;

    public function __construct()
    {
        $this->command = env('COMPOSER_PATH', 'composer');
    }

    public function execute()
    {
        if (empty($this->packages)) {
            return '';
        }

        $command = $this->command . ' ';
        $command .= $this->mode . ' ';
        $command .= implode(' ', $this->packages);
        $command .= $this->getOptions();

        return $command;
    }

    public function install()
    {
        $this->mode = 'require';
        return $this;
    }

    public function update()
    {
        $this->mode = 'update';
        return $this;
    }

    public function packages($packages)
    {
        $this->packages = (array)$packages;

        return $this;
    }

    /**
     * @param $mode
     * @return $this
     */
    public function setMode($mode)
    {
        $this->mode = $mode;

        return $this;
    }

    public function append($package)
    {
        $this->packages[] = $package;
    }

    /**
     * @param $options
     * @return $this
     */
    public function setOptions($options)
    {
        $this->options = (array)$options;

        return $this;
    }

    /**
     * @return string
     */
    public function getOptions()
    {
        $options = ' ';
        if ($this->options) {
            $options .= implode(' ', $this->options);
        }

        return $options;
    }
}